package org.robot.scm.platform.registry.strategy;

import cn.hutool.core.io.FileUtil;
import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.Message;
import it.tdlight.jni.TdApi.MessageContent;
import it.tdlight.jni.TdApi.MessagePhoto;
import java.io.File;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.platform.AbstractMonitor;
import org.robot.scm.platform.server.telegram.ScmTelegram;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.config.base.BasePlatform;
import org.robot.scm.pojos.enums.MessageTypeEnum;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.utils.RandomUtil;

/**
 * 图片类型信息处理
 *
 * @Author : Awn create on 2025/4/21 17:00
 */
@Slf4j
public class PhotoMessageHandler extends AbstractMessageHandler {


    @Override
    protected Class clazz() {
        return MessagePhoto.class;
    }

    @Override
    protected String doProcess(ScmTelegram scmTelegram, Message message, MessageContent messageContent) {
        MessagePhoto photo = (MessagePhoto) messageContent;
        TdApi.DownloadFile downloadFile = new TdApi.DownloadFile();
        downloadFile.fileId = photo.photo.sizes[photo.photo.sizes.length - 1].photo.id;
        downloadFile.priority = 1;
        downloadFile.synchronous = true;
        scmTelegram.getClient().send(downloadFile, file -> {
            String localPath = file.get().local.path;
            if (StringUtils.isBlank(localPath)) {
                return;
            }
            File srcFile = new File(localPath);
            String imageKey = RandomUtil.uuidNoLine();
            String fileExt = Optional.ofNullable(FileUtil.extName(srcFile)).map(String::toLowerCase).orElse("jpg");
            String filePath = imageKey + "." + fileExt;
            File destFile = new File("assets/telegram/" + filePath);
            FileUtil.move(srcFile, destFile, true);

            // http://47.99.155.172:58205/file/a381b3a981934285aeaccfc0a29f4833.sql";
            BasePlatform currentPlatform = AbstractMonitor.mainConfig.getPlatform(PlatformEnum.TELEGRAM);
            BaseConfig config = new BaseConfig(AbstractMonitor.mainConfig, currentPlatform);
            BasePlatform platform = config.get().getPlatform(PlatformEnum.TELEGRAM);
            // String fileWithCaption = "![](" + platform.getNoticeSrc() + "/file/" + filePath + ")";
            String fileWithCaption = "<img src='" + platform.getNoticeSrc() + "/file/" + filePath + "'/>";
            String content = StringUtils.isNotBlank(photo.caption.text) ? fileWithCaption + "\n\n" + photo.caption.text : fileWithCaption;
            sendMessage(scmTelegram, message, content, MessageTypeEnum.HTML);
        });

        return StringUtils.EMPTY;
    }
}
